package com.cal.calonecal.utils;

import com.cal.calonecal.mapper.UserInfoMapper;
import com.cal.calonecal.pojo.entity.UserInfo;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 76004
 * @apiNote
 * @date 2023/5/20 15:57
 */
@Component
public class UserUtil {
    @Autowired
    private UserInfoMapper userInfoMapper;
    public Long getUserId(HttpServletRequest httpServletRequest){
        return Long.valueOf(httpServletRequest.getHeader("Authorization"));
//        return 7L;
    }

    public Long getUserId(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        return getUserId(request);
//        return 8L;
    }

    public UserInfo getUser(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest();
        UserInfo userInfo = userInfoMapper.selectById(getUserId(httpServletRequest));
        if(userInfo == null){
            throw new RuntimeException("用户不存在");
        }
        return userInfo;
    }

    public UserInfo getUser(HttpServletRequest httpServletRequest){
        UserInfo userInfo = userInfoMapper.selectById(getUserId(httpServletRequest));
        if(userInfo == null){
            throw new RuntimeException("用户不存在");
        }
        return userInfo;
    }
}
